package jdbc;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.util.Scanner;

public class RegDemo {
    public static void main(String[] args) {
        /**完成用户注册功能
         * 程序启动后，要求用户在控制台上输入他的用户名，密码，昵称，年龄四项信息
         * 然后将信息插入到userinfo表中完成注册
         * 思想:应当将用户输入的信息拼接到SQL语句中形成INSERT,然后执行插入操作*/
             try {

                    Class.forName("com.mysql.cj.jdbc.Driver");
                    Connection connection = DriverManager.getConnection(
                            "jdbc:mysql://localhost:3306/tedu", "root", "root"
                    );
                    UserInfo userInfo =  InputUtil.getInputObject(new UserInfo(),"欢迎注册","注册");
                    System.out.println(userInfo);

                    Scanner scanner = new Scanner(System.in);
                    System.out.println("欢迎注册");
                    System.out.println("请输入用户名:");
                    String username = scanner.nextLine();

                    System.out.println("请输入密码:");
                    String password = scanner.nextLine();

                    System.out.println("请输入昵称:");
                    String nickname = scanner.nextLine();

                    System.out.println("请输入年龄:");
                    int age = Integer.parseInt(scanner.nextLine());

                    // 使用 PreparedStatement 避免 SQL 注入
                    String sql = "INSERT INTO userinfo (username, password, nickname, age) VALUES (?, ?, ?, ?)";
                    PreparedStatement preparedStatement = connection.prepareStatement(sql);
                    preparedStatement.setString(1, username);
                    preparedStatement.setString(2, password);
                    preparedStatement.setString(3, nickname);
                    preparedStatement.setInt(4, age);

                    int num = preparedStatement.executeUpdate();
                    if (num > 0) {
                        System.out.println("注册成功");
                    }

                    connection.close();
                    scanner.close();
                } catch (Exception e) {
                    e.printStackTrace();  // 打印异常堆栈信息，以便进一步诊断问题
                }
            }
        }


